<template>
    <div class="login">

        <div>
            <!--      <el-tabs v-model="activeName" type="border-card">-->

            <!--        <el-tab-pane label="密码登录" name="passwordLogin">-->
            <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"
                     :style="{'width':this.isPhone ? '300px': ''}"
            >
                <h3 class="title">{{title}}</h3>
                <el-form-item prop="username">
                    <el-input
                        v-model="loginForm.username"
                        type="text"
                        auto-complete="off"
                        placeholder="账号"
                    >
                        <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon"/>
                    </el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                        v-model="loginForm.password"
                        type="password"
                        auto-complete="off"
                        placeholder="密码"
                        @keyup.enter.native="handleLogin"
                    >
                        <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon"/>
                    </el-input>
                </el-form-item>

                <!--          <el-form-item prop="code" v-if="captchaOnOff">-->
                <!--            <el-input-->
                <!--              v-model="loginForm.code"-->
                <!--              auto-complete="off"-->
                <!--              placeholder="验证码"-->
                <!--              style="width: 63%"-->
                <!--              @keyup.enter.native="handleLogin"-->
                <!--            >-->
                <!--              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />-->
                <!--            </el-input>-->
                <!--            <div class="login-code">-->
                <!--              <img :src="codeUrl" @click="getCode" class="login-code-img"/>-->
                <!--            </div>-->
                <!--          </el-form-item>-->

                <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;">记住密码</el-checkbox>
                <el-form-item style="width:100%;">
                    <el-button
                        :loading="loading"
                        size="medium"
                        type="primary"
                        style="width:100%;"
                        @click.native.prevent="handleLogin"
                    >
                        <span v-if="!loading">登 录</span>
                        <span v-else>登 录 中...</span>
                    </el-button>
                    <div style="float: left;" v-if="register">
                        <router-link class="link-type" :to="'/forgetPassword'">忘记密码</router-link>
                    </div>
                    <div style="float: right;" v-if="register">
                        <router-link class="link-type" :to="'/register'">立即注册</router-link>
                    </div>
                </el-form-item>
            </el-form>
            <!--        </el-tab-pane>-->


            <!--      <el-tab-pane label="短信登录" name="smsLogin">-->

            <!--        <el-form ref="smsForm" :model="smsForm" :rules="smsRules" class="login-form">-->

            <!--          <el-form-item prop="phoneNumber">-->
            <!--            <el-input v-model="smsForm.phoneNumber" type="text" auto-complete="off" placeholder="手机号码">-->
            <!--              <svg-icon slot="prefix" icon-class="phone" class="el-input__icon input-icon" />-->
            <!--            </el-input>-->
            <!--          </el-form-item>-->

            <!--          <el-form-item prop="phoneCode">-->
            <!--            <el-input v-model="smsForm.phoneCode"-->
            <!--                      auto-complete="off"-->
            <!--                      placeholder="输入验证码"-->
            <!--                      style="width: 63%">-->
            <!--              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />-->
            <!--            </el-input>-->
            <!--            <div class="login-code">-->
            <!--              <el-button type="primary" plain :disabled="!phoneCodeStatus" @click="this.getPhoneCode" style="text-align: center; width: 100%">-->
            <!--                <span v-show="phoneCodeStatus">获取验证码</span>-->
            <!--                <span v-show="!phoneCodeStatus">{{countdownTime}}秒</span>-->
            <!--              </el-button>-->
            <!--            </div>-->
            <!--          </el-form-item>-->

            <!--          <el-form-item style="width:100%;">-->
            <!--            <el-button-->
            <!--              :loading="loading"-->
            <!--              size="medium"-->
            <!--              type="primary"-->
            <!--              style="width:100%;"-->
            <!--              @click.native.prevent="smsLogin">-->
            <!--              <span v-if="!loading">登 录</span>-->
            <!--              <span v-else>登 录 中...</span>-->
            <!--            </el-button>-->
            <!--&lt;!&ndash;            <div style="float: right;" v-if="register">&ndash;&gt;-->
            <!--&lt;!&ndash;              <router-link class="link-type" :to="'/register'">立即注册</router-link>&ndash;&gt;-->
            <!--&lt;!&ndash;            </div>&ndash;&gt;-->
            <!--          </el-form-item>-->

            <!--        </el-form>-->
            <!--        -->
            <!--      </el-tab-pane>-->

            <!--      </el-tabs>-->
        </div>
        <div class="el-login-footer">
            <a href="#" v-if="title==='宝秀智慧云平台'">海南宝秀节水科技股份有限公司</a>
            <a href="https://beian.miit.gov.cn" v-if="title==='智慧农业系统'">版权所有 湛江佳德科技有限公司 粤ICP备18102589号</a>
        </div>
    </div>
</template>

<script>
import { getCodeImg, getSmsCode } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
    name: 'Login',
    data() {
        return {
            countdownTime: null,
            phoneCodeStatus: true,
            activeName: 'passwordLogin',
            codeUrl: '',
            loginForm: {
                username: '',
                password: '',
                rememberMe: false,
                code: '',
                uuid: ''
            },
            loginRules: {
                username: [
                    { required: true, trigger: 'blur', message: '请输入您的账号' }
                ],
                password: [
                    { required: true, trigger: 'blur', message: '请输入您的密码' }
                ]
                // code: [{ required: true, trigger: "change", message: "请输入验证码" }]
            },
            smsForm: {
                phoneNumber: null,
                phoneCode: null
            },
            smsRules: {
                phoneNumber: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { min: 11, max: 11, message: '请输入11位长度的手机号码', trigger: 'blur' },
                    {
                        pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
                        message: '请输入正确的手机号码'
                    }
                ],
                phoneCode: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    { min: 4, max: 4, message: '请输入4位长度的验证码', trigger: 'blur' }
                ]
            },
            loading: false,
            // 验证码开关
            captchaOnOff: false,
            // 注册开关
            register: true,
            redirect: undefined,
            isPhone: false,
            title:''
        }
    },
    watch: {
        $route: {
            handler: function(route) {
                this.redirect = route.query && route.query.redirect
            },
            immediate: true
        }
    },
    created() {
        // // 获取当前域名
        const hostname = window.location.hostname
        console.log(hostname)
        this.hostname = hostname
        // 根据不同的域名设置不同的标题
        let pageTitle = '智慧农业系统' // 净化系统

        if ( hostname.includes('baoxiu')) {
            pageTitle = '宝秀智慧云平台'
        }else if (hostname.includes('agriculture')) {
            pageTitle = '智慧农业系统'
        }
        else if (hostname.includes('meida')){
            pageTitle = '智能碾米机'
        }
        this.title = pageTitle
        this.isPhone = this._isMobile()

        // console.log("l " + this.isPhone)

        // if (this._isMobile()) {
        //   // alert("手机端")
        //   this.isPhone = true
        // } else {
        //   // alert("电脑端")
        //   this.isPhone = false
        // }
        // this.getCode()
        this.getCookie()
    },
    methods: {

        _isMobile() {
            let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
            return flag
        },

        getPhoneCode() {
            let pattern = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
            if (pattern.test(this.smsForm.phoneNumber)) {
                // todo 发送验证码请求
                getSmsCode(this.smsForm).then(response => {
                    if (response.code === 200) {
                        this.$message.success('获取成功')
                        this.phoneCodeStatus = false
                        // 30秒
                        this.countdownTime = 30
                        const timeInterval = setInterval(() => {
                            this.countdownTime--
                            if (this.countdownTime <= 0) {
                                this.phoneCodeStatus = true
                                clearInterval(timeInterval)
                            }
                        }, 1000)
                    }
                    if (response.code === 500) {
                        this.$message.error(response.msg)
                    }
                }, error => {

                })
                // this.phoneCodeStatus = false
                // // 30秒
                // this.countdownTime = 30
                // const timeInterval = setInterval(() => {
                //   this.countdownTime--
                //   if (this.countdownTime <= 0) {
                //     this.phoneCodeStatus = true
                //     clearInterval(timeInterval)
                //   }
                // }, 1000)

            } else {
                this.$message.error('请输入正确的手机号')
            }
        },
        getCode() {
            getCodeImg().then(res => {
                this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff
                if (this.captchaOnOff) {
                    this.codeUrl = 'data:image/gif;base64,' + res.img
                    this.loginForm.uuid = res.uuid
                }
            })
        },
        getCookie() {
            const username = Cookies.get('username')
            const password = Cookies.get('password')
            const rememberMe = Cookies.get('rememberMe')
            this.loginForm = {
                username: username === undefined ? this.loginForm.username : username,
                password: password === undefined ? this.loginForm.password : decrypt(password),
                rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
            }
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    if (this.loginForm.rememberMe) {
                        Cookies.set('username', this.loginForm.username, { expires: 30 })
                        Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 })
                        Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 })
                    } else {
                        Cookies.remove('username')
                        Cookies.remove('password')
                        Cookies.remove('rememberMe')
                    }
                    this.$store.dispatch('Login', this.loginForm).then(() => {

                        // this.$router.push({ path: this.redirect || "/" }).catch(()=>{})
                        this.$router.push({ path: "/" }).catch(()=>{})
                        // this.redirect = "/control/loop"
                        // 登录后跳转到控制主页
                        // this.$router.push({path: this.redirect || "/control/loop"}).catch(() => {})

                    }).catch(() => {
                        this.loading = false
                        if (this.captchaOnOff) {
                            this.getCode()
                        }
                    })
                }
            })
        },
        smsLogin() {
            this.$refs.smsForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    this.$store.dispatch('smsLogin', this.smsForm).then(() => {
                        this.$router.push({ path: this.redirect || '/' }).catch(() => {
                        })
                    }).catch(() => {
                        this.loading = false
                    })
                }
            })
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url("../assets/images/login-background2.jpg");
    background-size: cover;
}

.title {
    margin: 0 auto 30px auto;
    text-align: center;
    color: #707070;
}

.login-form {
    border-radius: 6px;
    //background: rgba(255, 255, 255, 0.7); /* 半透明背景 */
    background-color: #ffffff; /* 半透明背景 */
    width: 400px;
    padding: 25px 25px 5px 25px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
    .el-input {
        height: 38px;

        input {
            height: 38px;
        }
    }

    .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 2px;
    }
}

.login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
}

.login-code {
    width: 33%;
    height: 38px;
    float: right;

    .el-button {
        width: 100%;
    }

    img {
        cursor: pointer;
        vertical-align: middle;
    }
}

.el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #7a7979;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
}

.login-code-img {
    height: 38px;
}
</style>
